/**
 * 
 */
package anyware.desktop.task;

import java.io.IOException;
import java.util.Collection;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import anyware.desktop.DesktopService;
import anyware.desktop.IndexException;
import anyware.desktop.IndexService;
import anyware.desktop.model.FileItem;

/**
 * @author keke
 * 
 */
@Scope("prototype")
@Component("indexTask")
public class IndexTask {
    private static final Logger LOG = LoggerFactory.getLogger(IndexTask.class);
    private DesktopService      desktopService;
    private IndexService        indexService;

    public void index() throws IOException {
        final long start = System.currentTimeMillis();
        final Collection<FileItem> items = desktopService.getToBeIndexedItems();
        if(LOG.isDebugEnabled()){
            LOG.debug("{} items to be indexed", items.size());
        }
        indexService.startIndex();
        try {
            for (final FileItem item : items) {
                try {
                    indexService.index(item);
                    item.getInfo().setDirty(false);
                    desktopService.saveItem(item);
                } catch (final IOException e) {
                    LOG.error(e.getMessage(), e);
                } catch (final IndexException e) {
                    LOG.error(e.getMessage(), e);
                }
            }
        } finally {
            indexService.commitIndex();
        }
        if (LOG.isInfoEnabled()) {
            LOG.info("Pref: index task cost {}", System.currentTimeMillis()
                    - start);
        }
    }

    @Resource
    public void setDesktopService(final DesktopService desktopService) {
        this.desktopService = desktopService;
    }

    @Resource
    public void setIndexService(final IndexService indexService) {
        this.indexService = indexService;
    }

}
